package com.xplay.xpocker.message.action.mahjong;

import com.xplay.xpocker.business.BusinessException;
import com.xplay.xpocker.entity.system.DissolutionEntity;
import com.xplay.xpocker.entity.system.UserDisInfo;
import com.xplay.xpocker.message.MessageToEnum;
import com.xplay.xpocker.message.action.MessageAnnotation;
import com.xplay.xpocker.message.action.MessageStrategy;
import com.xplay.xpocker.meta.MessageContent;
import com.xplay.xpocker.meta.realize.MahjongRoomEntity;
import com.xplay.xpocker.meta.realize.MahjongUserChannel;
import com.xplay.xpocker.service.mahjong.IDiskPartService;
import com.xplay.xpocker.util.BusinessAssertion;
import com.xplay.xpocker.util.DictionaryConst;
import com.xplay.xpocker.util.RedisUtil;
import org.apache.catalina.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import static com.xplay.xpocker.util.DictionaryConst.MahjongAction.DISSOLUTION;

/**
 * @author wanjie
 * @date 2021/3/17 21:43
 */
@MessageAnnotation(action = DISSOLUTION, type = {DictionaryConst.RoomTypeConst.WZ_MAHJONG})
@Service
public class MessageDissolution extends MessageStrategy {
    private static final Logger log = LoggerFactory.getLogger(MessageDissolution.class);

    @Override
    public void doMessage(MahjongUserChannel userChannel, MessageContent message, MahjongRoomEntity roomInfo) {
        Integer agreeState = null;
        try {
            agreeState = (Integer) message.getBody();
        } catch (Exception e) {
            throw new BusinessException("非法请求");
        }
        BusinessAssertion.isTrue("游戏还未开始可以直接退出", roomInfo.getState() == DictionaryConst.MahjongRoomState.CREATE);
        //如果游戏不是创建状态那么禁止退出游戏
        DissolutionEntity dissolutionEntity = roomInfo.getDissolutionEntity();
        if (dissolutionEntity == null || !dissolutionEntity.invalidDate()) {
            dissolutionEntity = new DissolutionEntity();
            dissolutionEntity.setDissolutionStartDate(new Date());
            HashMap<String, UserDisInfo> userDisMap = new HashMap<>();
            roomInfo.getAllUserInfo().forEach((uName, uInfo) -> {
                if (uName.equals(userChannel.getUserId())) {
                    userDisMap.put(uName, new UserDisInfo(uName, uInfo.getSysUser().getPortraitUrl(), DictionaryConst.RoomDissolutionConst.AGREE));
                } else {
                    userDisMap.put(uName, new UserDisInfo(uName, uInfo.getSysUser().getPortraitUrl(), DictionaryConst.RoomDissolutionConst.DEFAULT));
                }
            });
            dissolutionEntity.setUserDissolution(userDisMap);
            roomInfo.setDissolutionEntity(dissolutionEntity);
        }
        dissolutionEntity.setDisInfo(userChannel.getUserId(), userChannel.getSysUser().getPortraitUrl(), agreeState);
        message.setBody(dissolutionEntity);
        diskPart.get(roomInfo.getCode()).notifyMessage(message, null);
        Set<Map.Entry<String, UserDisInfo>> entries = dissolutionEntity.getUserDissolution().entrySet();
        // 是否全部都是同意
        Boolean allUserAgree = true;
        // 是否带有拒绝
        Boolean refuse = false;
        // 是否全部处理完毕
        Boolean allDen = true;
        for (Map.Entry<String, UserDisInfo> entry : entries) {
            if (allUserAgree && entry.getValue().getAgreeState() != DictionaryConst.RoomDissolutionConst.AGREE) {
                allUserAgree = false;
            }
            if (!refuse && entry.getValue().getAgreeState() == DictionaryConst.RoomDissolutionConst.REFUSE) {
                refuse = true;
            }
            if (allDen && entry.getValue().getAgreeState() == DictionaryConst.RoomDissolutionConst.DEFAULT) {
                allDen = false;
            }
        }
        // 如果全部处理完毕 并且带有拒绝的
        if (refuse && allDen) {
            roomInfo.setDissolutionEntity(null);
        }
        if (allUserAgree) {
            try {
                // 前端 2s 后关闭窗口
                Thread.sleep(1000l);
                roomInfo.setState(DictionaryConst.MahjongRoomState.OVER);
                roomInfo.setGameEndDate(new Date());
                updateRoomInfo(roomInfo);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
